<?php
//开启session
session_start();

class mysql{
    /** 连接
     * @return mysqli|string
     */
    private function links(){
        $servername = "47.106.247.65";
        $username = "root";
        $password = "root";
        $dbname = "test";
        $link = mysqli_connect($servername, $username, $password, $dbname);
        if ($link){
            return $link;
        }else{
            return mysqli_connect_error();
        }
    }

    /** 多条数据查询
     * @param $sql sql语句
     */
    function select($sql){
        $link = $this->links();
        if ($link){
            $arr = [];
            $res = mysqli_query($link,$sql);
            while ($data = mysqli_fetch_assoc($res)){
                $arr[] = $data;
            }
            return $arr;
        }else{
            return $link;
        }
    }

    /** 单条数据查询
     * @param $sql sql语句
     */
    function onedata($sql){
        $link = $this->links();
        if ($link){
            $res = mysqli_query($link,$sql);
            $arr = mysqli_fetch_assoc($res);
            return $arr;
        }else{
            return $link;
        }
    }

    /** 更新数据库表
     * @param $sql sql语句
     * @return array|string
     */
    function update($sql){
        $link = $this->links();
        if ($link){
            $res = mysqli_query($link,$sql);
            return $res;
        }else{
            return $link;
        }
    }

    /** 删除数据
     * @param $sql sql语句
     * @return array|string
     */
    function delete($sql){
        $link = $this->links();
        if ($link){
            $res = mysqli_query($link,$sql);
            return $res;
        }else{
            return $link;
        }
    }

    /** 插入数据
     * @param $sql sql语句
     * @return array|string
     */
    function insert($sql){
        $link = $this->links();
        if ($link){
            $res = mysqli_query($link,$sql);
            return $res;
        }else{
            return $link;
        }
    }

    /** 插入数组数据
     * @param $arr
     * @return bool|mysqli_result
     */
    function arr($arr){
        foreach($arr as $key => $value){
            $name = $arr[$key]['username'];
            $password = $arr[$key]['password'];
            $dd = $arr[$key]['dd'];
            $sql = "insert into test_table (id,username,password,dd) VALUES (NULL,'".$name."','".$password."','".$dd."');";
            $this->insert($sql);
        }
    }

}//end

/**
 * @param $str 提示语句
 * @param $num num秒
 * @param $url 超链接
 */
function alert($str,$num,$url){
    echo '<script type="text/javascript">alert("'.$str.'");</script>';
    header("Refresh: $num; url=".$url."");
    exit();
}
function alert2($url,$num,$str){
    header("Refresh: $num; url=".$url."");
    echo '<script type="text/javascript">alert("'.$str.'");</script>';
    exit();
}
?>

